<?php

namespace app\admin\model;


use control\EncryptionMethod;

class Admin extends Base
{
    /**
     * @return array
     * 数据验证规则
     */
    public function filedRules(){
        return [
            "action"=>["add","update","status","delete","login","updatePwd"],
            "form"=>[
                'id|id|用户ID|update|status|delete' => 'require|minNumber:2',
                'id|id|用户ID|updatePwd' => 'require',
                'username|username|用户名|add|update|login'=>'require',
                'nickname|nickname|昵称|add|update'=>'require',
                'role_ids|role_ids|角色|add|update'=>'require',
                'oldpwd|oldpwd|旧密码|updatePwd'=>'require|min:6',
                'password|password|密码|add|login|updatePwd'=>'require|min:6',
                'repwd|repwd|确认密码|updatePwd'=>'require|min:6',
                'status|status|用户状态|status'=>'require|number',
            ],
        ];
    }
    /**
     * @return array
     * 搜索验证规则
     */
    public  function searchRule(){
        return [
            "index"=>[
                "start|createdate" =>"date_time|>=",
                "end|createdate"   =>"date_time|<=",
                "username|username"=>"normal|like",
                "nickname|nickname"=>"normal|like",
            ],
        ];
    }

    /**
     * 用户登录
     */
    public function checkUser(){
        $data=$this->validate();
        $userinfo = $this->where('username', trim($data["username"]))->find()->toArray();
        if($userinfo && $userinfo["password"] == EncryptionMethod::ts_sha1($data["password"])){
            session('admin',$userinfo);
            \think\facade\Session::save();
            successReturn("提示: 登录成功！");
        }else{
            errorReturn("错误: 账号或密码错误！");
        }
    }
    /**
     * 修改管理员自己的密码
     */
    public function updatePwd(){
        $data=$this->validate();
        $user = session('admin');
        if($data["password"]!=$data["repwd"]){
            errorReturn("错误: 新密码和确认密码不一致！");
        }
        if($user["password"]!=EncryptionMethod::ts_sha1(base64_encode(sha1($data['oldpwd'],true)))){
            errorReturn("错误: 旧密码错误！");
        }
        if($this->update(['password' => EncryptionMethod::ts_sha1(base64_encode(sha1($data['password'],true)))], ['id' => $user['id']])){
            session(null);
            \think\facade\Session::save();
            successReturn("提示: 密码修改成功！");
        }else{
            errorReturn("错误: 密码修改失败！");
        }
    }
}